﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Pur;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Sales;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Pur
{
    public partial class frmMaintainPurchaseOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public PurPurchaseOrderEntity SelectedPurchaseOrder { get; set; }
        private List<PurPurchaseOrderItemEntity> DeleteList = new List<PurPurchaseOrderItemEntity>();

        private List<PurApplicationItemEntity> mListApplicationItems;
        private List<PurPurchaseOrderItemEntity> mListPurchaseOrderItems;
        #endregion

        #region Constructor
        public frmMaintainPurchaseOrder()
        {
            InitializeComponent();
            if (SelectedPurchaseOrder == null)
            {
                SelectedPurchaseOrder = new PurPurchaseOrderEntity();
                SelectedPurchaseOrder.PurchaseOrderId = Guid.NewGuid().ToString();
            }
        }

        public frmMaintainPurchaseOrder(List<PurApplicationItemEntity> list, MstSupplierEntity supplier)
        {
            InitializeComponent();
            if (SelectedPurchaseOrder == null)
            {
                SelectedPurchaseOrder = new PurPurchaseOrderEntity();
                SelectedPurchaseOrder.PurchaseOrderId = Guid.NewGuid().ToString();
            }
            SetFieldsBySupplier(supplier);
            if (list != null)
            {
                BindComboBox();
                SetPurApplicationFields(list, true);
            }
        }
        #endregion

        #region Functions
        private void InitializaFields()
        {
            //MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByCode(CommonParameter.MyCompanyCode);
            //if (customer != null)
            //{
            //    //txtCustomer.Text = customer.CustomerName;
            //    txtCustomer.Tag = customer;
            //    MstCustomerContactEntity contact = UICommonFunctions.GetMainCustomerContact(customer.CustomerId);
            //    if (contact != null)
            //    {
            //        txtCustomerContact.Text = contact.ContactName;
            //        txtCustomerContactPhone.Text = contact.ContactMobilephone;
            //    }
            //}
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtPurchasePerson.Tag = person;
                    txtPurchasePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(person.DepartmentId);
                if (department != null)
                {
                    txtDepartment.Text = department.DepartmentName;
                    txtDepartment.Tag = department;
                }

                //临时，客户无法看到，暂时指定为自己
                MstCustomerEntity mCustomer = MstCustomerBs.GetMstCustomerByID("3cc4236a-a619-4cd6-8a0d-87fcc513b869");
                if (mCustomer == null)
                    return;
                txtCustomer.Text = mCustomer.CustomerName;
                txtCustomer.Tag = mCustomer;
                MstCustomerContactEntity contact = UICommonFunctions.GetMainCustomerContact(mCustomer.CustomerId);
                if (contact != null)
                {
                    txtCustomerContact.Text = contact.ContactName;
                    txtCustomerContactPhone.Text = contact.ContactMobilephone;
                }
            }
        }

        private void SetFieldsBySupplier(MstSupplierEntity supplier)
        {
            if (supplier != null)
            {
                txtSupplier.Tag = supplier;
                txtSupplier.Text = supplier.SupplierName;
                MstSupplierContactEntity contact = UICommonFunctions.GetMainSupplierContact(supplier.SupplierId);
                if (contact != null)
                {
                    txtSupplierContact.Text = contact.ContactName;
                    txtSupplierContactPhone.Text = contact.ContactMobilephone;
                }
            }
            else
            {
                if (supplier != null)
                {
                    txtSupplier.Tag = null;
                    txtSupplier.Text = "";
                    txtSupplierContact.Text = "";
                    txtSupplierContactPhone.Text = "";
                }
            }
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PURST", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPaymentType, "PAYWAY", true);
            UICommon.UICommonFunctions.BindComboboxByEnum(cmbIsProductPurchase, typeof(PurchaseCategory), typeof(int), true);
            cmbIsProductPurchase.SelectedIndex = 0;
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPurchaseType, "PURTYPE", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private void BindDataGridDetail()
        {
            string purchaseOrderId = "";
            if (SelectedPurchaseOrder != null)
            {
                purchaseOrderId = SelectedPurchaseOrder.PurchaseOrderId;
            }
            DataSet ds = PurPurchaseOrderItemBs.GetDataSetByPurchaseOrderID(purchaseOrderId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;

            DataTable dt2 = PurPurchaseOrderItemBs.GetPurchaseProductionDetailByPurchaseOrderID(purchaseOrderId);
            gvMain2.DataSource = dt2;

            DeleteList = new List<PurPurchaseOrderItemEntity>();
        }

        private void SetDataGridDetailByPurchaseOrderItems()
        {
            if (mListPurchaseOrderItems == null || mListPurchaseOrderItems.Count == 0)
            {
                return;
            }
            if (gvMain.DataSource == null)
            {
                BindDataGridDetail();
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (PurPurchaseOrderItemEntity entity in mListPurchaseOrderItems)
            {
                DataRow dr = dt.NewRow();
                dr["PURCHASE_ITEM_ID"] = entity.PurchaseItemId;
                dr["PURCHASE_ORDER_ID"] = entity.PurchaseOrderId;
                MstProductEntity product = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                if (product != null)
                {
                    dr["PRODUCT_ID"] = product.ProductId;
                    dr["PRODUCT_CODE"] = product.ProductCode;
                    dr["PRODUCT_NAME"] = product.ProductName;
                    dr["PRODUCT_SPEC_IN"] = product.ProductSpecIn;
                    dr["MATERIAL"] = product.Material;
                    dr["UNIT"] = product.Unit;
                    dr["DESCRIPTION"] = product.Description;
                }
                dr["QTY"] = entity.Qty;
                dr["TAX_RATE"] = 0.17;
                dr["PRICE_NO_TAX"] = decimal.Round(entity.PriceNoTax, 2);
                dr["TOTAL_AMOUNT"] = decimal.Round(entity.PriceNoTax * entity.Qty, 2);
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private PurQuoteItemEntity GetFromListByPurItemId(List<PurQuoteItemEntity> list, string purchaseItemId)
        {
            if (list == null || list.Count == 0)
            {
                return null;
            }
            List<PurQuoteItemEntity> result = (from entity in list where entity.PurchaseItemId == purchaseItemId select entity).ToList<PurQuoteItemEntity>();
            if (result != null && result.Count > 0)
            {
                return result[0];
            }
            return null;
        }

        private void SetDataByQuoteOrder(PurQuoteOrderEntity quoteOrder)
        {
            if (quoteOrder == null)
            {
                txtQuoteOrder.Text = "";
                txtQuoteOrder.Tag = null;
                SelectedPurchaseOrder.QuoteOrderId = null;
                return;
            }
            txtQuoteOrder.Tag = quoteOrder;
            txtQuoteOrder.Text = quoteOrder.QuoteOrderCode;
            SelectedPurchaseOrder.QuoteOrderId = quoteOrder.QuoteOrderId;
            MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(quoteOrder.SupplierId);
            SetFieldsBySupplier(supplier);
            List<PurQuoteItemEntity> list = PurQuoteItemBs.GetByQuoteOrderID(quoteOrder.QuoteOrderId);
            if (list != null && list.Count > 0)
            {
                DataTable dt = gvMain.DataSource as DataTable;
                foreach (DataRow dr in dt.Rows)
                {
                    PurPurchaseOrderItemEntity item = new PurPurchaseOrderItemEntity(dr);
                    if (item != null)
                    {
                        PurQuoteItemEntity entity = GetFromListByPurItemId(list, item.PurchaseItemId);
                        if (entity != null)
                        {
                            item.PriceNoTax = entity.PriceNoTax;
                            dr["PRICE_NO_TAX"] = decimal.Round(item.PriceNoTax, 2);
                            dr["TOTAL_AMOUNT"] = decimal.Round(item.PriceNoTax * item.Qty, 2);
                        }
                    }
                }
            }
            ResetTotalAmount();
        }

        private void ResetTax()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["TOTAL_AMOUNT"] != null && CommonFunctions.IsDecimal(dr["TOTAL_AMOUNT"].ToString()))
                {
                    decimal tax = CommonFunctions.ToDecimal(dr["TAX_RATE"]) + 1;
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE_NO_TAX"]);
                    if (cboxIsTax.Checked)
                    {
                        price = price * tax;
                    }
                    else
                    {
                        price = price / tax;
                    }
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"]) * price;
                    dr["PRICE_NO_TAX"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                    totalAmount += amount;
                }
            }
        }

        private void ResetTotalAmount()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach(DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["PRICE_NO_TAX"].ToString()) == false &&
                   CommonFunctions.IsDecimal(dr["PRICE_NO_TAX"].ToString()) &&
                    string.IsNullOrEmpty(dr["QTY"].ToString()) == false &&
                    CommonFunctions.IsDecimal(dr["QTY"].ToString()))
                {
                    decimal qty = Convert.ToDecimal(dr["QTY"].ToString());
                    decimal price = Convert.ToDecimal(dr["PRICE_NO_TAX"].ToString());
                    dr["TOTAL_AMOUNT"] = Math.Round(price * qty, 2);
                    totalAmount += qty * price;
                }
            }
            txtTotalAmount.Text = decimal.Round(totalAmount, 2).ToString();
        }

        private bool IsProductInList(List<PurPurchaseOrderItemEntity> list, string productId, out PurPurchaseOrderItemEntity poi)
        {
            poi = null;
            if (list == null || list.Count == 0)
            {
                return false;
            }
            foreach (PurPurchaseOrderItemEntity item in list)
            {
                if (item == null)
                {
                    continue;
                }
                if (item.ProductId == productId)
                {
                    poi = item;
                    return true;
                }
            }
            return false;
        }

        private void SetPurApplicationFields(List<PurApplicationItemEntity> list, bool setDetail)
        {
            mListApplicationItems = list;
            mListPurchaseOrderItems = new List<PurPurchaseOrderItemEntity>();
            if (list != null && list.Count > 0)
            {
                foreach (PurApplicationItemEntity entity in list)
                {
                    PurPurchaseOrderItemEntity item = null;
                    //modify by Mars.Chen on 2012-04-20 for Do not combine PurchaseApplicationList
                    item = new PurPurchaseOrderItemEntity();
                    item.PurchaseItemId = Guid.NewGuid().ToString();
                    item.PurchaseOrderId = SelectedPurchaseOrder.PurchaseOrderId;
                    item.ProductId = entity.ProductId;
                    item.Qty = entity.Qty;
                    item.ArrivedQty = 0;
                    item.PriceNoTax = 0;
                    item.TaxRate = Convert.ToDecimal("0.17");
                    item.Remark = "";
                    item.ProductSpecIn = entity.ProductSpecIn;
                    item.ProductSpecOut = entity.ProductSpecOut;

                    item.PurchaseOrderItemDetailList = new List<PurPurchaseOrderItemDetailEntity>();
                    PurPurchaseOrderItemDetailEntity detail = new PurPurchaseOrderItemDetailEntity();
                    detail.ApplicationItemId = entity.ApplicationItemId;
                    detail.PurchaseItemId = item.PurchaseItemId;
                    item.PurchaseOrderItemDetailList.Add(detail);

                    mListPurchaseOrderItems.Add(item);
                }
                if (setDetail)
                {
                    //Set Detail
                    if (gvMain.DataSource != null)
                    {
                        DataTable dt = gvMain.DataSource as DataTable;
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr.RowState != DataRowState.Added)
                            {
                                PurPurchaseOrderItemEntity entity = new PurPurchaseOrderItemEntity(dr);
                                DeleteList.Add(entity);
                            }
                            dt.Rows.Remove(dr);
                        }
                    }
                    SetDataGridDetailByPurchaseOrderItems();
                }
            }
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedPurchaseOrder == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(SelectedPurchaseOrder.CustomerId) == false)
            {
                MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedPurchaseOrder.CustomerId);
                if (customer != null)
                {
                    txtCustomer.Tag = customer;
                    txtCustomer.Text = customer.CustomerName;
                    MstCustomerContactEntity contact = UICommonFunctions.GetMainCustomerContact(customer.CustomerId);
                    if (contact != null)
                    {
                        txtCustomerContact.Text = contact.ContactName;
                        txtCustomerContactPhone.Text = contact.ContactMobilephone;
                    }
                }
            }
            if (string.IsNullOrEmpty(SelectedPurchaseOrder.SupplierId) == false)
            {
                MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(SelectedPurchaseOrder.SupplierId);
                if (supplier != null)
                {
                    SetFieldsBySupplier(supplier);
                }
            }
            txtPurchaseOrderCode.Text = SelectedPurchaseOrder.PurchaseOrderCode;
            if (string.IsNullOrEmpty(txtPurchaseOrderCode.Text))
            {
                txtPurchaseOrderCode.Text = "自动生成";
            }
            if (string.IsNullOrEmpty(SelectedPurchaseOrder.PurchaseDepartment) == false)
            {
                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(SelectedPurchaseOrder.PurchaseDepartment);
                if (department != null)
                {
                    txtDepartment.Tag = department;
                    txtDepartment.Text = department.DepartmentName;
                }
            }
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtPurchasePerson.Tag = person;
                    txtPurchasePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(person.DepartmentId);
                if (department != null)
                {
                    txtDepartment.Text = department.DepartmentName;
                    txtDepartment.Tag = department;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedPurchaseOrder.PurchasePerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedPurchaseOrder.PurchasePerson);
                    if (person != null)
                    {
                        txtPurchasePerson.Tag = person;
                        txtPurchasePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            if (string.IsNullOrEmpty(SelectedPurchaseOrder.QuoteOrderId) == false)
            {
                PurQuoteOrderEntity quoteOrder = PurQuoteOrderBs.GetPurQuoteOrderByID(SelectedPurchaseOrder.QuoteOrderId);
                if (quoteOrder != null)
                {
                    txtQuoteOrder.Tag = quoteOrder;
                    txtQuoteOrder.Text = quoteOrder.QuoteOrderCode;
                }
            }
            txtTotalAmount.Text = SelectedPurchaseOrder.TotalAmount.ToString();
            cmbCurrency.SetSelectedValue(SelectedPurchaseOrder.Currency);
            cmbPaymentType.SetSelectedValue(SelectedPurchaseOrder.PaymentType);
            if (SelectedPurchaseOrder.IsTax == 1)
            {
                cboxIsTax.Checked = true;
            }
            else
            {
                cboxIsTax.Checked = false;
            }
            dtpDeliveryRequiredDate.EditValue = SelectedPurchaseOrder.DeliveryRequiredDate;
            dtpDeliveryPlanDate.EditValue = SelectedPurchaseOrder.DeliveryPlanDate;
            dtpPurchaseDate.EditValue = SelectedPurchaseOrder.PurchaseDate;
            cmbIsProductPurchase.SetSelectedValue(SelectedPurchaseOrder.IsProductPurchase);
            cmbPurchaseType.SetSelectedValue(SelectedPurchaseOrder.PurchaseType);
            cmbStatus.SetSelectedValue(SelectedPurchaseOrder.Status);
            txtRemark.Text = SelectedPurchaseOrder.Remark;
            txtAttached.Text = SelectedPurchaseOrder.AttachedFile;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedPurchaseOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedPurchaseOrder.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedPurchaseOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedPurchaseOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedPurchaseOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedPurchaseOrder.ApprovedBy);
        }

        private void SetEntity()
        {
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                SelectedPurchaseOrder.SupplierId = ((MstSupplierEntity)txtSupplier.Tag).SupplierId;
            }
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SelectedPurchaseOrder.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            if (txtDepartment.Tag != null && txtDepartment.Tag.GetType() == typeof(MstDepartmentEntity))
            {
                SelectedPurchaseOrder.PurchaseDepartment = ((MstDepartmentEntity)txtDepartment.Tag).DepartmentId;
            }
            if (txtPurchasePerson.Tag != null && txtPurchasePerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedPurchaseOrder.PurchasePerson = ((MstPersonEntity)txtPurchasePerson.Tag).PersonId;
            }
            if (txtQuoteOrder.Tag != null && txtQuoteOrder.Tag.GetType() == typeof(PurQuoteOrderEntity))
            {
                SelectedPurchaseOrder.QuoteOrderId = ((PurQuoteOrderEntity)txtQuoteOrder.Tag).QuoteOrderId;
            }
            SelectedPurchaseOrder.TotalAmount = CommonFunctions.ToDecimal(txtTotalAmount.Text);
            if (cmbCurrency.SelectedValue != null && cmbCurrency.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurchaseOrder.Currency = cmbCurrency.SelectedValue.ToString().Trim();
            }
            if (cmbPaymentType.SelectedValue != null && cmbPaymentType.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurchaseOrder.PaymentType = cmbPaymentType.SelectedValue.ToString().Trim();
            }
            if (cboxIsTax.Checked)
            {
                SelectedPurchaseOrder.IsTax = 1;
            }
            else
            {
                SelectedPurchaseOrder.IsTax = 0;
            }
            if (dtpPurchaseDate.EditValue!=null)
            {
                SelectedPurchaseOrder.PurchaseDate = Convert.ToDateTime(dtpPurchaseDate.EditValue);
            }
            if (dtpDeliveryRequiredDate.EditValue!=null)
            {
                SelectedPurchaseOrder.DeliveryRequiredDate = Convert.ToDateTime(dtpDeliveryRequiredDate.EditValue);
            }
            if (dtpDeliveryPlanDate.EditValue!=null)
            {
                SelectedPurchaseOrder.DeliveryPlanDate = Convert.ToDateTime(dtpDeliveryPlanDate.EditValue);
            }
            if (cmbIsProductPurchase.SelectedValue != null && cmbIsProductPurchase.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurchaseOrder.IsProductPurchase = CommonFunctions.ToInt32(cmbIsProductPurchase.SelectedValue);
            }
            if (cmbPurchaseType.SelectedValue != null && cmbPurchaseType.SelectedValue.ToString().Trim() != "")
            {
                SelectedPurchaseOrder.PurchaseType = cmbPurchaseType.SelectedValue.ToString().Trim();
            }
            SelectedPurchaseOrder.Status = PurchaseOrderStatus.PURST02.ToString();
            SelectedPurchaseOrder.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedPurchaseOrder.CreatedDate = DateTime.Now;
                SelectedPurchaseOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedPurchaseOrder.LastModifiedDate = DateTime.Now;
                SelectedPurchaseOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (ThisActionType == ActionType.Approve)
            {
                if (string.IsNullOrEmpty(txtSupplier.Text))
                {
                    MessageBox.Show("供应商不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtDepartment.Text))
            {
                MessageBox.Show("采购部门不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtPurchasePerson.Text))
            {
                MessageBox.Show("采购人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbCurrency.SelectedValue == null || cmbCurrency.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("货币种类不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpPurchaseDate.EditValue==null)
            {
                MessageBox.Show("采购日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbIsProductPurchase.SelectedValue == null || cmbIsProductPurchase.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("采购方式不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbPurchaseType.SelectedValue == null || cmbPurchaseType.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("采购类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvMain.DataSource == null)
            {
                MessageBox.Show("采购明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurPurchaseOrderBs.SavePurchaseOrder(true, SelectedPurchaseOrder, dt, mListPurchaseOrderItems, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = PurPurchaseOrderBs.SavePurchaseOrder(false, SelectedPurchaseOrder, dt, mListPurchaseOrderItems, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedPurchaseOrder.ApprovedDate = DateTime.Now;
                    SelectedPurchaseOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = PurPurchaseOrderBs.ApprovePurchaseOrder(SelectedPurchaseOrder);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Confirm)
                {
                    bool isSuccessful = PurPurchaseOrderBs.UpdatePurPurchaseOrder(SelectedPurchaseOrder);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("确认失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool UploadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        SelectedPurchaseOrder.AttachedFile = SelectedPurchaseOrder.PurchaseOrderCode + "." + CommonFunctions.GetFileExtension(fileFullName);
                        string path = service.PurchaseOrderAttachedPath();
                        byte[] bytes = CommonFunctions.FileToByte(fileFullName);
                        string errMsg = "";
                        bool result = service.UploadFileNew(bytes, path + "\\" + SelectedPurchaseOrder.AttachedFile, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        result = PurPurchaseOrderBs.UpdatePurPurchaseOrder(SelectedPurchaseOrder);
                        if (result)
                        {
                            txtAttached.Text = SelectedPurchaseOrder.AttachedFile;
                        }
                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool DownloadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.PurchaseOrderAttachedPath();
                        byte[] bytes = service.DownloadFileNew(path + "\\" + SelectedPurchaseOrder.AttachedFile, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(fileFullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            if (ThisActionType == ActionType.New)
            {
                InitializaFields();
                if (mListPurchaseOrderItems != null)
                {
                    gvMain.ContextMenuStrip = null;
                }
                else
                {
                    gvMain.ContextMenuStrip = ContextMenuStrip;
                }
            }
            else if (ThisActionType == ActionType.Modify)
            {
                if (SelectedPurchaseOrder != null)
                {
                    List<PurPurchaseOrderItemDetailEntity> list = PurPurchaseOrderItemDetailBs.GetPurPurchaseOrderItemDetailByPurOrderId(SelectedPurchaseOrder.PurchaseOrderId);
                    if (list != null && list.Count > 0)
                    {
                        gvMain.ContextMenuStrip = null;
                    }
                    else
                    {
                        gvMain.ContextMenuStrip = ContextMenuStrip;
                    }
                }
            }
            BindComboBox();
            if (ThisActionType != ActionType.New)
            {
                SetFields();
            }   
        }

        DataRow drItemSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drItemSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void cboxIsTax_CheckedChanged(object sender, EventArgs e)
        {
            if (cboxIsTax.Checked)
            {
                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价（含税）";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计（含税）";
            }
            else
            {
                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计";
            }
            ResetTax();
            ResetTotalAmount();
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.View)
            {
                return;
            }
            if (ThisActionType == ActionType.New || SelectedPurchaseOrder == null)
            {
                MessageBox.Show("请先保存后再上传文件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            OpenFileDialog fd = new OpenFileDialog();
            fd.Multiselect = false;
            fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = UploadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("没有可下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(SelectedPurchaseOrder.AttachedFile))
            {
                MessageBox.Show("没有找到可以下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = SelectedPurchaseOrder.AttachedFile;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = DownloadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void txtSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                if (!frm.SelectedSupplier.Status.Equals("STATUS03"))
                {
                    MessageBox.Show("选择的供应商尚未审核!","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }
                txtSupplier.Text = frm.SelectedSupplier.SupplierName;
                txtSupplier.Tag = frm.SelectedSupplier;

                MstSupplierContactEntity contact = UICommonFunctions.GetMainSupplierContact(frm.SelectedSupplier.SupplierId);
                if (contact != null)
                {
                    txtSupplierContact.Text = contact.ContactName;
                    txtSupplierContactPhone.Text = contact.ContactMobilephone;
                }
            }
            else
            {
                txtSupplier.Text = "";
                txtSupplier.Tag = null;

                txtSupplierContact.Text = "";
                txtSupplierContactPhone.Text = "";
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                txtCustomer.Text = frm.SelectedCustomer.CustomerName;
                txtCustomer.Tag = frm.SelectedCustomer;

                MstCustomerContactEntity contact = UICommonFunctions.GetMainCustomerContact(frm.SelectedCustomer.CustomerId);
                if (contact != null)
                {
                    txtCustomerContact.Text = contact.ContactName;
                    txtCustomerContactPhone.Text = contact.ContactMobilephone;
                }
            }
            else
            {
                txtCustomer.Text = "";
                txtCustomer.Tag = null;

                txtCustomerContact.Text = "";
                txtCustomerContactPhone.Text = "";
            }
        }

        private void txtDepartment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainDepartmentQuery frm = new frmMaintainDepartmentQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedDepartment != null)
            {
                txtDepartment.Text = frm.SelectedDepartment.DepartmentName;
                txtDepartment.Tag = frm.SelectedDepartment;
            }
            else
            {
                txtDepartment.Text = "";
                txtDepartment.Tag = null;
            }
        }

        private void txtPurchasePerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (txtDepartment.Tag != null && txtDepartment.Tag.GetType() == typeof(MstDepartmentEntity))
            {
                frm = new frmMaintainEmployeeQuery((MstDepartmentEntity)txtDepartment.Tag);
            }
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtPurchasePerson.Text = frm.SelectedPerson.NameCn;
                txtPurchasePerson.Tag = frm.SelectedPerson;

                MstDepartmentEntity department = MstDepartmentBs.GetMstDepartmentByID(frm.SelectedPerson.DepartmentId);
                if (department != null)
                {
                    txtDepartment.Text = department.DepartmentName;
                    txtDepartment.Tag = department;
                }
            }
            else
            {
                txtPurchasePerson.Text = "";
                txtPurchasePerson.Tag = null;
            }
        }

        private void txtQuoteOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseQuoteOrderQuery frm = new frmMaintainPurchaseQuoteOrderQuery(SelectedPurchaseOrder);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurQuoteOrder != null)
            {
                SetDataByQuoteOrder(frm.SelectedPurQuoteOrder);
            }
            else
            {
                SetDataByQuoteOrder(null);
            }
        }

        private void tsmNew_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["PURCHASE_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["PURCHASE_ORDER_ID"] = SelectedPurchaseOrder.PurchaseOrderId;
            dr["TAX_RATE"] = 0.17;
            dt.Rows.Add(dr);
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (drItemSelected == null)
            {
                return;
            }
            if (drItemSelected.RowState != DataRowState.Added)
            {
                PurPurchaseOrderItemEntity entity = new PurPurchaseOrderItemEntity(drItemSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(drItemSelected);
            ResetTotalAmount();
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drItemSelected == null)
            {
                return;
            }
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drItemSelected["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drItemSelected["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
                drItemSelected["PRODUCT_SPEC_IN"] = frm.SelectedProduct.ProductSpecIn;
                drItemSelected["MATERIAL"] = frm.SelectedProduct.Material;
                drItemSelected["UNIT"] = frm.SelectedProduct.Unit;
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Name.Equals("colQTY") || e.Column.Name.Equals("colPRICE_NO_TAX"))
            {
                decimal unitPrice = 0;
                decimal qty = 0;
                if (string.IsNullOrEmpty(drItemSelected["PRICE_NO_TAX"].ToString()))
                {
                    return;
                }
                if (string.IsNullOrEmpty(drItemSelected["QTY"].ToString()))
                {
                    return;
                }
                unitPrice = Convert.ToDecimal(drItemSelected["PRICE_NO_TAX"]);
                qty = Convert.ToDecimal(drItemSelected["QTY"]);
                drItemSelected["TOTAL_AMOUNT"]=decimal.Round(unitPrice * qty, 2);
                ResetTotalAmount();
            }
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedPurchaseOrder = new PurPurchaseOrderEntity();
                SelectedPurchaseOrder.PurchaseOrderId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedPurchaseOrder == null)
            {
                return;
            }
            if (ThisActionType == ActionType.Approve)
            {
                SelectedPurchaseOrder.Status = PurchaseOrderStatus.PURST03.ToString();
            }
            else if (ThisActionType == ActionType.Confirm)
            {
                SelectedPurchaseOrder.Status = PurchaseOrderStatus.PURST035.ToString();
                if (dtpDeliveryPlanDate.EditValue!=null)
                {
                    SelectedPurchaseOrder.DeliveryPlanDate = (DateTime)dtpDeliveryPlanDate.EditValue;
                }
                SelectedPurchaseOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                SelectedPurchaseOrder.LastModifiedDate = DateTime.Now;
            }
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedPurchaseOrder == null)
            {
                return;
            }
            SelectedPurchaseOrder.Status = PurchaseOrderStatus.PURST04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        //private void cmbIsProductPurchase_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    if (cmbIsProductPurchase.SelectedValue != null && cmbIsProductPurchase.SelectedValue.ToString() == PurchaseCategory.生产类采购.GetHashCode().ToString())
        //    {
        //        gvDetail.ResetHeadTextColorColumns = "colPRODUCT_NAME;colQTY;colMATERIAL";
        //        colMATERIAL.HeaderCell.Style.ForeColor = gvDetail.ColumnHeadTextColor;
        //    }
        //    else
        //    {
        //        gvDetail.ResetHeadTextColorColumns = "colPRODUCT_NAME;colQTY";
        //        colMATERIAL.HeaderCell.Style.ForeColor = Color.Black;
        //    }
        //}


        #endregion

    }
}
